package com.lh_travel.lohas.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.util.TimeUtils;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lh_travel.lohas.R;
import com.lh_travel.lohas.adapter.CommonAdapter;
import com.lh_travel.lohas.adapter.MyFragmentAdapter;
import com.lh_travel.lohas.adapter.ViewHolder;
import com.lh_travel.lohas.base.api;
import com.lh_travel.lohas.base.baseActivity;
import com.lh_travel.lohas.domain.DafultMessageEvent;
import com.lh_travel.lohas.domain.Record;
import com.lh_travel.lohas.domain.SearchTips;
import com.lh_travel.lohas.fragment.ChCityFragment;
import com.lh_travel.lohas.utils.Preferences;
import com.lh_travel.lohas.widget.FlowViewGroup;
import com.lh_travel.lohas.widget.ScrollListView;
import com.tamic.novate.Throwable;
import com.tamic.novate.callback.RxResultCallback;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by aaron on 2018/6/7.
 */

public class ContentSearchActivity extends baseActivity {

    private ViewPager vp_content;
    private TabLayout tabLayout;
    private LinearLayout ll_search;
    private LinearLayout ll_near;
    private ScrollListView lv_tisp;
    private LinearLayout ll_history;
    private EditText ed_search;
    private LinearLayout ll_city;
    private InputMethodManager mInputMethodManager;
    private List<SearchTips.Position> tipsList = new ArrayList<>();
    private CommonAdapter tipsAdapter;
    private ArrayList permission;
    private Button btn_cancle;
    private LinearLayout ll_head;
    private TextView tv_title;
    private FlowViewGroup fvg_his;
    private List<Record> hisList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_search_content);

        findView();
        bindListner();
        ensureUI();

    }

    @Override
    public void findView() {
        vp_content = (ViewPager) findViewById(R.id.vp_content);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        ed_search = (EditText) findViewById(R.id.ed_search);
        ll_city = (LinearLayout) findViewById(R.id.ll_city);
        btn_cancle = (Button) findViewById(R.id.btn_cancle);

        ll_search = (LinearLayout) findViewById(R.id.ll_search);
        ll_near = (LinearLayout) findViewById(R.id.ll_near);
        lv_tisp = (ScrollListView) findViewById(R.id.lv_tisp);
        ll_history = (LinearLayout) findViewById(R.id.ll_history);
        ll_head = (LinearLayout) findViewById(R.id.ll_head);
        tv_title = (TextView) findViewById(R.id.tv_title);
        fvg_his = (FlowViewGroup) findViewById(R.id.fvg_his);

    }

    @Override
    public void bindListner() {
        ed_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ed_search.setFocusable(true);//设置输入框可聚集
                ed_search.setFocusableInTouchMode(true);//设置触摸聚焦
                ed_search.requestFocus();//请求焦点
                ed_search.findFocus();//获取焦点
                mInputMethodManager.showSoftInput(ed_search, InputMethodManager.SHOW_FORCED);// 显示输入法
            }
        });

        ed_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == 66) {

                    mInputMethodManager.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);// 隐藏输入法
                    ed_search.setFocusable(false);

                    String keyWord = ed_search.getText().toString().trim();
                    DafultMessageEvent events = new DafultMessageEvent();

                    events.TAG = "ContentSearchActivity";
                    events.belong = "cn";
                    events.message = keyWord;

                    EventBus.getDefault().post(events);

                    finish();
                }

                return false;
            }
        });

        ed_search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    ll_city.setVisibility(View.GONE);

                    ll_search.setVisibility(View.VISIBLE);

                } else {
                    ll_city.setVisibility(View.VISIBLE);

                    ll_search.setVisibility(View.GONE);

                }
            }
        });

        ed_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                String text = ed_search.getText().toString().trim();

                if (text.length() > 0) {

                    //请求模糊搜索的接口
                    new api(mContext).prompt(text, new RxResultCallback<SearchTips>() {
                        @Override
                        public void onNext(Object tag, int code, String message, SearchTips response) {

                            if (code == 200) {

                                tipsList.clear();
                                tipsList.addAll(response.hotel.cn);
                                tipsList.addAll(response.hotel.foreign);

                                if (tipsAdapter == null) {
                                    setTipsList();

                                } else {

                                    tipsAdapter.setmDatas(tipsList);

                                    tipsAdapter.notifyDataSetChanged();
                                }

                                refreshHead(response.position);

                            }else {

                                if (tipsAdapter != null) {

                                    tipsList.clear();

                                    tipsAdapter.notifyDataSetChanged();

                                    ll_head.setVisibility(View.GONE);
                                }

                            }
                        }

                        @Override
                        public void onError(Object tag, Throwable e) {

                        }

                        @Override
                        public void onCancel(Object tag, Throwable e) {

                        }
                    });

                }
            }
        });

        ll_near.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mApp.getPreference(Preferences.LOCAL.LAT) == null) {

                    showMyDialog("失败", "请检查并申请定位权限", "申请权限", "取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            dialog.dismiss();
                            startActivity(getAppDetailSettingIntent());
                        }
                    });

                } else {

                    //用lat和lng作为参数跳转到酒店列表页面
                    DafultMessageEvent event = new DafultMessageEvent();

                    event.TAG = "ContentSearchActivity2";
                    event.belong = mApp.getPreference(Preferences.LOCAL.COUNTRY);
                    event.message = mApp.getPreference(Preferences.LOCAL.CITY);

                    EventBus.getDefault().post(event);

                    if (mInputMethodManager.isActive()) {
                        mInputMethodManager.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
                    }

                    finish();
                }

            }
        });

        btn_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mInputMethodManager.isActive()) {
                    mInputMethodManager.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
                }

                finish();
            }
        });

    }

    private void refreshHead(final SearchTips.Position position) {

        if (position.is_null == 1){

            ll_head.setVisibility(View.VISIBLE);
            tv_title.setText(position.title);

            ll_head.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    DafultMessageEvent event = new DafultMessageEvent();

                    event.TAG = "ContentSearchActivity";
                    event.belong = position.belong;
                    event.message = position.address;

                    EventBus.getDefault().post(event);

                    if (mInputMethodManager.isActive()) {
                        mInputMethodManager.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
                    }

                    finish();

                }
            });

        }else {
            ll_head.setVisibility(View.GONE);
        }

    }

    @Override
    public void ensureUI() {
        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        initFragment();

        initHis();
    }

    private void initHis() {

        hisList = mApp.getListPrefernce(Preferences.LOCAL.SEARCH_KEYWORD);

        if (hisList.size() > 0){

           for (int i = 0; i < hisList.size(); i++){

               Record record = hisList.get(i);

               TextView text = (TextView) LayoutInflater.from(this).inflate(R.layout.item_his, fvg_his, false);

               text.setText(record.title);

               final DafultMessageEvent event = new DafultMessageEvent();

               event.TAG = "ContentSearchActivity";
               event.belong = record.belong;
               event.message = record.title;

               text.setOnClickListener(new View.OnClickListener() {

                   @Override
                   public void onClick(View v) {

                       EventBus.getDefault().post(event);

                       if (mInputMethodManager.isActive()) {
                           mInputMethodManager.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
                       }

                       finish();
                   }
               });

               fvg_his.addView(text);
           }

            ll_history.setVisibility(View.VISIBLE);
        }else {
            ll_history.setVisibility(View.GONE);
        }

    }

    private void setTipsList() {
        tipsAdapter = new CommonAdapter<SearchTips.Position>(mContext, tipsList, R.layout.item_tips) {

            @Override
            public void convert(ViewHolder helper, SearchTips.Position item, int position) {

                helper.setText(R.id.tv_title, item.title);

            }
        };

        lv_tisp.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                DafultMessageEvent event = new DafultMessageEvent();

                event.TAG = "ContentSearchActivity";
                event.belong = tipsList.get(position).belong;
                event.message = tipsList.get(position).title;

                EventBus.getDefault().post(event);

                if (mInputMethodManager.isActive()) {
                    mInputMethodManager.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
                }

                finish();
            }
        });

        lv_tisp.setAdapter(tipsAdapter);
    }

    private void initFragment() {
        ArrayList<Fragment> mList = new ArrayList<>();

        ArrayList<String> titleList = new ArrayList<>();

        titleList.add(mContext.getString(R.string.city_ch));
        titleList.add(mContext.getString(R.string.city_word));

        ChCityFragment cityFragment1 = new ChCityFragment(true);
        ChCityFragment cityFragment2 = new ChCityFragment(false);

        mList.add(cityFragment1);
        mList.add(cityFragment2);

        MyFragmentAdapter mAdapter = new MyFragmentAdapter(getSupportFragmentManager(), titleList, mList);

        vp_content.setAdapter(mAdapter);
        vp_content.setOffscreenPageLimit(mList.size());
        tabLayout.setupWithViewPager(vp_content, true);

        vp_content.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (position == 0) {

                    mApp.setPreference(Preferences.LOCAL.COUNTRY, "cn");

                } else {

                    mApp.setPreference(Preferences.LOCAL.COUNTRY, "foreign");
                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
